package jsu.yym.tiktok.service;

import jsu.yym.tiktok.pojo.User;
import jsu.yym.tiktok.pojo.UserData;
import jsu.yym.tiktok.mapper.UserDataMapper;
import jsu.yym.tiktok.mapper.VideoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserDataService {
    @Autowired
    private UserDataMapper userDataMapper;
    @Autowired
    private VideoMapper videoMapper;

    //根据用户的浏览记录，为用户更新标签
    public String AnalyzeData(String id)
    {
        String Label="";
        HashMap<String, Integer> map = new HashMap<>();
        List<UserData> userDataList = userDataMapper.getUserData(id);
        if (Objects.isNull(userDataList)) {
            return null;//用户还没有浏览记录
        }
        for (UserData u:userDataList) {
            String label = videoMapper.getLabelByPkId(u.getVideo_id());
            if(Objects.isNull(map.get(label))) {
                map.put(label, 1);
            }
            else {
                int count = map.get(label);
                map.put(label,count+1);
            }
        }
        //分析map集合，根据值进行排序
        // 将HashMap转换为包含键值对的List
        List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
        // 使用Comparator对List进行排序（按值升序）
        Collections.sort(list, Map.Entry.comparingByValue());
        // 可选择按值降序排序
        // Collections.sort(list, Map.Entry.comparingByValue(Comparator.reverseOrder()));
        // 将排序后的List转换为新的HashMap
        LinkedHashMap<String, Integer> sortedMap = list.stream()
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
        for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) {
            String key = entry.getKey();
            Label=Label+key;
        }
        return Label;
    }

    // 根据标签计算用户之间的标签相似度
    public double calculateLabelSimilarity(User user1, User user2) {
        String label1 = user1.getTarge();
        String label2 = user2.getTarge();

        // 实现标签相似度计算逻辑
        // 可以使用字符串相似度算法，如Jaccard相似度、余弦相似度等
        // 返回值范围通常在0到1之间
        double labelSimilarity = calculateLabelSimilarityBetweenLabels(label1, label2);

        return labelSimilarity;
    }

    // 根据浏览历史计算用户之间的浏览历史相似度
    public double calculateHistorySimilarity(User user1, User user2) {
        List<UserData> history1 = userDataMapper.getUserData(user1.getUsername());
        List<UserData> history2 = userDataMapper.getUserData(user2.getUsername());

        // 实现浏览历史相似度计算逻辑
        // 可以考虑使用Jaccard相似度、余弦相似度等算法
        double historySimilarity = calculateHistorySimilarityBetweenHistories(history1, history2);

        return historySimilarity;
    }

    // 综合标签相似度和浏览历史相似度计算用户相似度
    public double calculateUserSimilarity(User user1, User user2) {
        double labelSimilarity = calculateLabelSimilarity(user1, user2);
        double historySimilarity = calculateHistorySimilarity(user1, user2);

        // 实现综合相似度计算逻辑，可以加权平均或其他方式
        double userSimilarity = (labelSimilarity + historySimilarity) / 2;

        return userSimilarity;
    }

    public double calculateLabelSimilarityBetweenLabels(String label1, String label2) {
        // 将标签1和标签2分割为标签项的集合
        Set<String> set1 = new HashSet<>(Arrays.asList(label1.split(",")));
        Set<String> set2 = new HashSet<>(Arrays.asList(label2.split(",")));

        // 计算交集的大小
        Set<String> intersection = new HashSet<>(set1);
        intersection.retainAll(set2);

        // 计算并集的大小
        Set<String> union = new HashSet<>(set1);
        union.addAll(set2);

        // 计算Jaccard相似度
        if (union.isEmpty()) {
            return 0.0; // 防止除零错误
        } else {
            double jaccardSimilarity = (double) intersection.size() / union.size();
            return jaccardSimilarity;
        }
    }

    public double calculateHistorySimilarityBetweenHistories(List<UserData> history1, List<UserData> history2) {
        // 将浏览历史1和浏览历史2分别表示为标签项的集合
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> set2 = new HashSet<>();

        for (UserData userData : history1) {
            set1.add(userData.getVideo_id());
        }

        for (UserData userData : history2) {
            set2.add(userData.getVideo_id());
        }

        // 计算交集的大小
        Set<Integer> intersection = new HashSet<>(set1);
        intersection.retainAll(set2);

        // 计算并集的大小
        Set<Integer> union = new HashSet<>(set1);
        union.addAll(set2);

        // 计算Jaccard相似度
        if (union.isEmpty()) {
            return 0.0; // 防止除零错误
        } else {
            double jaccardSimilarity = (double) intersection.size() / union.size();
            return jaccardSimilarity;
        }
    }


}
